import { ChangeDetectionStrategy, Component, Injector, OnInit } from '@angular/core';
import { FileSaveService } from '@basic';
import { STColumn, STRes } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { UrlOfSystemTable } from '@routes/system/_base';
import { SystemConfigService } from '@routes/system/config/config.service';
import { SystemOssService } from '@routes/system/oss/oss.service';

import { OssUploadFileComponent } from '../upload-file/upload-file.component';
import { OssUploadImgComponent } from '../upload-img/upload-img.component';

@Component({
    selector: 'app-system-oss-list',
    templateUrl: './oss-list.component.html',
    styleUrls: ['./oss-list.component.less'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class SystemOssListComponent extends UrlOfSystemTable implements OnInit {
    columns: STColumn[] = [
        {
            title: '编号',
            fixed: 'left',
            width: '50px',
            type: 'checkbox',
            className: 'text-center',
            exported: false
        },
        {
            title: '对象存储主键',
            index: 'ossId',
            className: 'text-center',
            width: '200px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.ossId }) }
        },
        {
            title: '文件名',
            index: 'fileName',
            className: 'text-center',
            width: '200px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.fileName }) }
        },
        {
            title: '原名',
            index: 'originalName',
            className: 'text-center',
            width: '200px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.originalName }) }
        },
        {
            title: '文件后缀',
            index: 'fileSuffix',
            className: 'text-center',
            width: '100px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.fileSuffix }) }
        },
        {
            title: '文件展示',
            index: 'url',
            className: 'text-center',
            width: '200px',
            render: 'filePreviewCustom'
        },
        {
            title: '创建时间',
            index: 'createTime',
            className: 'text-center',
            width: '200px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.createTime }) }
        },
        {
            title: '上传人',
            index: 'createBy',
            className: 'text-center',
            width: '150px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.createBy }) }
        },
        {
            title: '服务商',
            index: 'service',
            className: 'text-center',
            width: '100px',
            type: 'widget',
            widget: { type: 'long-text', params: ({ record }) => ({ text: record.service }) }
        },
        {
            title: '操作',
            width: '230px',
            className: 'text-center',
            buttons: [
                {
                    text: '下载',
                    iif: item => item.roleId !== 1,
                    // tooltip: `下载`,
                    acl: ['admin', 'system:oss:download'],
                    icon: 'download',
                    click: item => this.downloadFile(item)
                },
                {
                    text: '删除',
                    iif: item => item.roleId !== 1,
                    // tooltip: '删除',
                    acl: ['admin', 'system:oss:remove'],
                    icon: 'delete',
                    className: 'text-error',
                    click: item => this.delFile(item)
                }
            ]
        }
    ];
    searchSchema: SFSchema = {
        properties: {
            fileName: {
                type: 'string',
                title: '文件名',
                ui: {
                    placeholder: '请输入文件名'
                }
            },
            originalName: {
                type: 'string',
                title: '原名',
                ui: {
                    placeholder: '请输入原名'
                }
            },
            fileSuffix: {
                type: 'string',
                title: '文件后缀',
                ui: {
                    placeholder: '请输入文件后缀'
                }
            },
            range: {
                type: 'string',
                title: '创建时间',
                ui: {
                    widget: 'date',
                    mode: 'range',
                    placeholder: '选择时间段'
                }
            },
            createBy: {
                type: 'string',
                title: '上传人',
                ui: {
                    placeholder: '请输入上传人'
                }
            },
            service: {
                type: 'string',
                title: '服务商',
                ui: {
                    placeholder: '请输入服务商'
                }
            }
        }
    };
    url: string = this.apiUrl.resource.list;

    previewListResource: boolean = false;

    override resReName: STRes = {
        reName: {
            total: 'total',
            list: 'rows'
        },
        process: data => {
            this.getNewPreviewConfig();
            return data;
        }
    };

    constructor(
        protected override injector: Injector,
        private ossSrv: SystemOssService,
        private fileSrv: FileSaveService,
        protected configSrv: SystemConfigService
    ) {
        super(injector);
    }

    getNewPreviewConfig() {
        this.configSrv.getConfigKey('sys.oss.previewListResource').subscribe(res => {
            this.previewListResource = res.msg === undefined ? true : res.msg === 'true';
            this.cdRef.detectChanges();
        });
    }

    showImgFile(fileSuffix: string) {
        let arr = ['png', 'jpg', 'jpeg'];
        return arr.some(type => {
            return fileSuffix.indexOf(type) > -1;
        });
    }

    handlePreviewListResource(previewListResource: boolean) {
        let text = previewListResource ? '启用' : '停用';
        this.modalSrv.confirm({
            nzTitle: '提示',
            nzContent: `确认要"${text}""预览列表图片"配置吗?`,
            nzOnOk: () =>
                this.configSrv.updateConfigByKey('sys.oss.previewListResource', previewListResource).subscribe(res => {
                    if (res.isComplete) {
                        this.msg.success(`${text}成功`);
                        this.st.reload();
                    }
                })
        });
    }
    uploadFile() {
        this.modal
            .creatStaticModal(OssUploadFileComponent, {}, 'md', {
                nzTitle: '文件上传'
            })
            .subscribe(res => {
                if (res) {
                    this.st.reload();
                }
            });
    }
    uploadImg() {
        this.modal
            .creatStaticModal(OssUploadImgComponent, {}, 'md', {
                nzTitle: '图片上传'
            })
            .subscribe(res => {
                if (res) {
                    this.st.reload();
                }
            });
    }
    delFiles(items: any[]) {
        this.modalSrv.confirm({
            nzTitle: '删除提示',
            nzContent: `是否确认删除OSS对象存储编号为 ${items.map(xx => xx.ossId).join(',')} 的数据项？`,
            nzOnOk: () =>
                this.ossSrv.delOss(items.map(xx => xx.ossId).join(',')).subscribe(res => {
                    if (res.isComplete) {
                        this.msg.success('删除成功');
                    }
                    this.st.reload();
                })
        });
    }
    downloadFile(item: any) {
        this.fileSrv.oss(item.ossId);
    }
    delFile(item: any) {
        this.modalSrv.confirm({
            nzTitle: '删除提示',
            nzContent: `是否确认删除OSS对象存储编号为 ${item.ossId} 的数据项？`,
            nzOnOk: () =>
                this.ossSrv.delOss(item.ossId.toString()).subscribe(res => {
                    if (res.isComplete) {
                        this.msg.success('删除成功');
                    }
                    this.st.reload();
                })
        });
    }

    navToConfig() {
        this.router.navigate(['/system/oss-config/index']).then();
    }
}
